package com.atguigu.gmall.list.controller.api;

import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.list.service.GoodsService;
import com.atguigu.gmall.list.service.SearchService;
import com.atguigu.gmall.model.list.Goods;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/list")
public class ApiListController {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    private GoodsService goodsService;

    /**
     * 更新商品incrHotScore
     * @param skuId
     * @return
     */
    @GetMapping("/incrHotScore/{skuId}")
    public Boolean incrHotScore(@PathVariable("skuId")Long skuId){
        //1 校验参数
        if (skuId == null) {
            throw new GmallException("参数错误", null);
        }

        //2 掉用业务层的方法
        try{
            goodsService.incrHotScoreBySkuId(skuId);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除指定skuId的商品es中的数据
     *
     * @param skuId
     */
    @GetMapping("/removeBySkuId/{skuId}")
    public Boolean removeBySkuId(@PathVariable("skuId") Long skuId) {
        //1 校验参数
        if (skuId == null) {
            throw new GmallException("参数错误", null);
        }

        //2 调用业务层的方法
        try {
            goodsService.removeGoodsFromEsBySkuId(skuId);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 添加数据到es中
     *
     * @param skuId
     */
    @GetMapping("/save/{skuId}")
    public Boolean saveBySkuId(@PathVariable("skuId") Long skuId) {
        //1 校验参数
        if (skuId == null) {
            throw new GmallException("参数错误", null);
        }

        //2 调用业务层方法
        try {
            goodsService.addSkuFromDbToEsBySkuId(skuId);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 创建索引、映射
     *
     * @return
     */
    @GetMapping("/createIndex")
    public Result createIndex() {
        //调用模板对象
        elasticsearchRestTemplate.createIndex(Goods.class);
        elasticsearchRestTemplate.putMapping(Goods.class);

        return Result.ok();
    }
}
